package com.example.dormitorymanagement.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dormitorymanagement.entity.Classmanagement;
import com.example.dormitorymanagement.entity.Dormroom;
import com.example.dormitorymanagement.entity.Student;
import com.example.dormitorymanagement.entity.simplestudent;
import com.example.dormitorymanagement.exception.AbnormalPermissions;
import com.example.dormitorymanagement.mapper.DormroomMapper;
import com.example.dormitorymanagement.mapper.StudentMapper;
import com.example.dormitorymanagement.service.impl.DormroomServiceImpl;
import com.example.dormitorymanagement.service.impl.StudentServiceImpl;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//@CrossOrigin
@RestController
@RequestMapping("/dormroom")
@Api(tags = "宿舍管理，权限低：只能查询数据，权限高：数据的增删改查")
public class DormroomController {

    @Autowired
    private DormroomMapper dormroomMapper;

    @Autowired
    private DormroomServiceImpl dormroomServiceimpl;

    @Autowired
    private StudentServiceImpl studentserviceimpl;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private com.example.dormitorymanagement.service.impl.suthorityservice suthorityservice;


    @PostMapping(value = "/addormodify")
    @ApiOperation(value = "添加或者修改宿舍")
    public Map<String, Object> addormodify(@RequestBody Dormroom dormroom, HttpServletRequest request) throws AbnormalPermissions {
        Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0) {
            return map;
        }

        if (dormroom.getId() != null && dormroom.getId() != 0) {
            //修改之前，先查看数据库中是否有该数据

            QueryWrapper<Dormroom> dormroomQueryWrapper = new QueryWrapper<>();

            dormroomQueryWrapper
                    .eq("building", dormroom.getBuilding())
                    .eq("number", dormroom.getNumber())
                    .ne("id", dormroom.getId());

            if (dormroomMapper.selectCount(dormroomQueryWrapper) != 0) {

                map.put("stat", false);

                map.put("message", "修改失败，要修改的数据已经存在");

                return map;

            }

            //修改的时候，要同步修改学生里面的值
            dormroomQueryWrapper.clear();

            dormroomQueryWrapper.eq("id", dormroom.getId());

            Dormroom lingshidormroom = dormroomMapper.selectOne(dormroomQueryWrapper);//获取这个id原来的数据

            String sushe = (lingshidormroom.getBuilding() + "栋") + lingshidormroom.getNumber();

            dormroomQueryWrapper.clear();

            UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();

            String updatedormroom = (dormroom.getBuilding() + "栋") + dormroom.getNumber();

            studentUpdateWrapper.set("student_dormitory", updatedormroom).eq("student_dormitory", sushe);

            int delete = studentMapper.update(null, studentUpdateWrapper);

            if (delete != 0) {
                if (dormroomServiceimpl.updateById(dormroom)) {

                    map.put("stat", true);
                    map.put("message", "更新成功，本次更新的数据：" + dormroom);

                } else {

                    map.put("stat", false);
                    map.put("message", "更新失败");

                }

                return map;
            }


            if (dormroomServiceimpl.updateById(dormroom)) {

                map.put("stat", true);
                map.put("message", "更新成功，本次更新的数据：" + dormroom);

            } else {

                map.put("stat", false);

                map.put("message", "更新失败");

            }

            return map;
        }

        //增加前查看对应的宿舍是否存在
        QueryWrapper<Dormroom> dormroomQueryWrapper = new QueryWrapper<>();

        dormroomQueryWrapper.eq("building", dormroom.getBuilding()).eq("number", dormroom.getNumber());

        if (dormroomMapper.selectCount(dormroomQueryWrapper) != 0) {

            map.put("stat", false);
            map.put("message", "存在该宿舍");
            return map;
        }

        //添加的时候，先把宿舍中人数设为0，后期再通过代码来获取该宿舍中对应的人数
        dormroom.setTotalpeople(0);

        boolean save = dormroomServiceimpl.save(dormroom);

        if (save) {

            map.put("stat", true);

            map.put("message", "添加成功");

            return map;

        } else {

            map.put("stat", false);

            map.put("message", "添加失败");

            return map;

        }

    }

    @GetMapping(value = "/getdormroom")
    @ApiOperation(value = "通过条件来获取宿舍管理中的所有数据，一页10条数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "building", value = "第几栋宿舍，不传值则默认获取所有楼栋的数据", dataType = "int"),
            @ApiImplicitParam(name = "pc", value = "第几页，不传值默认为第一页", dataType = "int")
    })
    public Map<String, Object> dormroom(Integer building, Integer pc) {

        Map<String, Object> map = new HashMap<>();

        if (pc == null) {
            pc = 1;
        }

        QueryWrapper<Dormroom> dormroomQueryWrapper = new QueryWrapper<>();

        map.put("building", building);

        dormroomQueryWrapper.allEq(map, false).orderByAsc("building").orderByAsc("number");

        map.clear();

        Page<Dormroom> dormroomPage = new Page<>(pc, 10);

        dormroomMapper.selectPage(dormroomPage, dormroomQueryWrapper);

        if (pc > dormroomPage.getPages()) {
            map.put("stat", false);

            map.put("message", "页数越界，总页数：" + dormroomPage.getPages() + "，当前页数:" + dormroomPage.getCurrent());

            return map;
        }

        List<Dormroom> records = dormroomPage.getRecords();

        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

        records.forEach(dormroom -> {

            String dormitory = dormroom.getBuilding() + "栋" + dormroom.getNumber();

            studentQueryWrapper.eq("student_dormitory", dormitory);

            Integer integer = studentMapper.selectCount(studentQueryWrapper);

            dormroom.setTotalpeople(integer);

            studentQueryWrapper.clear();

        });
        map.put("stat", true);
        map.put("records", records);
        map.put("pages", dormroomPage.getPages());
        map.put("page", dormroomPage.getCurrent());
        map.put("total", dormroomPage.getTotal());
        map.put("current", dormroomPage.getCurrent());
        map.put("hasPrevious", dormroomPage.hasPrevious());
        map.put("hasNext", dormroomPage.hasNext());
        map.put("yfp","2");
        return map;

    }


    @GetMapping(value = "/deletedormroom")
    @ApiOperation(value = "通过id来删除宿舍管理对象")
    public Map<String, Object> deletedeommroom(@ApiParam(name = "id", value = "要删除的宿舍管理对象的id", required = true) @RequestParam(value = "id") Integer id,
                                               HttpServletRequest request) throws AbnormalPermissions {

      Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0) {
            return map;
        }
        UpdateWrapper<Dormroom> dormroomUpdateWrapper = new UpdateWrapper<>();

        dormroomUpdateWrapper.eq("id", id);

        int result = dormroomMapper.delete(dormroomUpdateWrapper);

        if (result == 1) {

            map.put("stat", true);
            map.put("message", "删除成功");

            return map;
        }

        map.put("stat", false);
        map.put("message", "删除失败，请联系管理员");

        return map;


    }

    @GetMapping(value = "/getbuilding")
    @ApiOperation(value = "获取宿舍的楼号")
    public Map<String, Object> getbuilding() {

        QueryWrapper<Dormroom> dormroomQueryWrapper = new QueryWrapper<>();

        dormroomQueryWrapper.groupBy("building").orderByAsc("building");

        List<Dormroom> dormrooms = dormroomMapper.selectList(dormroomQueryWrapper);

        List<Integer> buildings = new ArrayList<>();

        dormrooms.forEach(dormroom -> {

            buildings.add(dormroom.getBuilding());

        });

        Map<String, Object> map = new HashMap<>();

        map.put("stat", true);
        map.put("bulidings", buildings);

        return map;

    }

    @GetMapping(value = "/getnumber")
    @ApiOperation(value = "通过宿舍的楼号来获取该楼下的所有宿舍")
    public Map<String, Object> getnumber(@ApiParam(name = "building", value = "第几栋", required = true) @RequestParam(name = "building") Integer building) {
        QueryWrapper<Dormroom> dormroomQueryWrapper = new QueryWrapper<>();

        dormroomQueryWrapper.eq("building", building).groupBy("number");

        List<Dormroom> dormrooms = dormroomMapper.selectList(dormroomQueryWrapper);

        List<Integer> numbers = new ArrayList<>();

        dormrooms.forEach(dormroom -> {

            numbers.add(dormroom.getNumber());

        });

        Map<String, Object> map = new HashMap<>();

        map.put("stat", true);
        map.put("bulidings", numbers);

        return map;

    }

    @GetMapping(value = "/getstudentlist")
    @ApiOperation(value = "通过宿舍管理的id来获取该宿舍下有哪些学生居住")
    public Map<String, Object> getstudentlist(@ApiParam(name = "id", value = "宿舍管理的id", required = true) @RequestParam Integer id,
                                              HttpServletRequest request)
    {

        Map<String, Object> map = new HashMap<>();

        QueryWrapper<Dormroom> dormroomQueryWrapper = new QueryWrapper<>();

        dormroomQueryWrapper.eq("id",id);

        Dormroom dormroom = dormroomMapper.selectOne(dormroomQueryWrapper);

        String ss = dormroom.getBuilding() + "栋" + dormroom.getNumber();

        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

        studentQueryWrapper.eq("student_dormitory",ss);

        List<Student> students = studentMapper.selectList(studentQueryWrapper);

        int size = students.size();

        if (size == 0)
        {
            map.put("stat",false);

            map.put("message","没有找到数据");

            return map;
        }

        map.put("stat",true);

        map.put("students",students);

        return map;

    }


}
















